onlineMusic.controller('search', ['$rootScope', '$scope', '$http',
  function ($rootScope, $scope, $http) {
    
    $scope.search_results;  
    $scope.search_inprogress;
    $scope.current_played;
    $scope.search_query;
    $scope.pre_player   = false;
    $scope.search_error = false;

    setInterval( function() { 
        $scope.updatePlaylist()
    } , 2000);

    $scope.loadResults = function(q) {

        if($scope.search_query.length < 3){
            $scope.search_error = true;
            return false;
        }
        
        $scope.search_inprogress  = true;
        $scope.search_error       = false;
        $scope.search_results     = false;
        
        $http.get('api/search/'+q).success(function(data) {
            $scope.search_inprogress  = false;
            $scope.search_results     = data;
        });
    }
    
    $scope.playSong = function(id){
        $scope.search_inprogress = true;
        $http.get('api/stream/'+id).success(function(data) {
            $scope.pre_play_link      = data;
            $scope.search_inprogress  = false;
            $scope.current_played     = id;
            
            if(!$scope.pre_player){
                audiojs.events.ready(function() {
                    a = audiojs.createAll();
                    $scope.pre_player = a[0];
                });  
            }
            
            ;
            
            $scope.pre_player.load( $scope.pre_play_link );
            $scope.pre_player.play();
        });   
    }
    
    $scope.addSong = function(){
        $http.get('api/playlist/add/'+$scope.current_played).success(function(data) {
            if(data == 'error'){
                alert('Этот трек уже есть в плейлисте!');
                return false;
            }
            $scope.updatePlaylist();
        });
    }
    
    $scope.updatePlaylist = function(){
        $http.get('api/playlist').success(function(data) {
            $rootScope.playlist = data;
            for(i = 0; i < data.length; i++){
                if(data[i].current_played == 1){
                    $rootScope.current_song = data[i];
                    $rootScope.next_song    = data[i+1];
                }
            }
        });  
    }
}]);
